import { BasePlugin } from '../plugin-system/base-plugin.js'
import { createLogger } from '../utils/logger.js'

const logger = createLogger('SearchReplace')

/**
 * 搜索替换插件
 * 提供代码搜索和替换功能
 */
export class SearchReplacePlugin extends BasePlugin {
    constructor(editor, options = {}) {
        super(editor, {
            // 默认配置
            caseSensitive: false,
            wholeWord: false,
            useRegex: false,
            wrapSearch: true,
            ...options
        })
        
        // 状态管理
        this.searchText = ''
        this.replaceText = ''
        this.currentIndex = -1
        this.matches = []
        this.isSearchVisible = false
        this.isReplaceVisible = false  // 新增：控制替换框显示
        
        // DOM 元素
        this.searchDialog = null
        this.searchInput = null
        this.replaceInput = null
        this.replaceSection = null  // 新增：替换区域
        this.toggleReplaceBtn = null  // 新增：切换替换框按钮
        
        // 高亮相关
        this.highlights = []
        this.currentHighlight = null
    }
    
    initialize() {
        // 插件初始化逻辑
        this.createSearchDialog()
    }
    
    onEnable() {
        // 监听编辑器事件
        this.editor.on('editor:keydown', this.handleKeyDown.bind(this))
        
        // 确保DOM创建
        if (!this.searchDialog) {
            this.createSearchDialog()
        }
        
        this.emit('searchReplace:enabled')
    }
    
    onDisable() {
        // 移除事件监听
        this.editor.off('editor:keydown', this.handleKeyDown.bind(this))
        
        // 隐藏搜索对话框
        this.hideSearch()
        
        this.emit('searchReplace:disabled')
    }
    
    onDestroy() {
        this.hideSearch()
        this.clearHighlights()
        if (this.searchDialog && this.searchDialog.parentNode) {
            this.searchDialog.parentNode.removeChild(this.searchDialog)
        }
    }
    
    /**
     * 创建搜索对话框
     */
    createSearchDialog() {
        // 创建主容器
        this.searchDialog = document.createElement('div')
        this.searchDialog.className = 'search-replace-dialog'
        this.searchDialog.style.cssText = `
            position: fixed;
            top: 60px;
            right: 20px;
            width: 380px;
            background: #252526;
            border: 1px solid #3c3c3c;
            color: #cccccc;
            display: none;
            z-index: 1000;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            font-size: 13px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.35);
            border-radius: 0;
            user-select: none;
        `
        
        // 创建标题栏（可拖拽）
        const titleBar = document.createElement('div')
        titleBar.className = 'search-title-bar'
        titleBar.style.cssText = `
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 6px 8px;
            background: #2d2d30;
            border-bottom: 1px solid #3c3c3c;
            cursor: move;
            font-size: 11px;
            color: #cccccc;
        `
        titleBar.innerHTML = `
            <div style="display: flex; align-items: center; gap: 4px;">
                <span style="font-size: 12px;">🔍</span>
                <span>查找和替换</span>
            </div>
            <button class="close-btn" style="
                background: none;
                border: none;
                color: #cccccc;
                font-size: 16px;
                cursor: pointer;
                padding: 2px 4px;
                line-height: 1;
                opacity: 0.7;
                transition: opacity 0.2s;
            " onmouseover="this.style.opacity='1'" onmouseout="this.style.opacity='0.7'">×</button>
        `
        
        // 创建搜索区域
        const searchSection = document.createElement('div')
        searchSection.className = 'search-section'
        searchSection.style.cssText = 'padding: 6px 8px; background: #252526;'
        
        // 搜索输入框容器
        const searchInputContainer = document.createElement('div')
        searchInputContainer.style.cssText = `
            display: flex;
            align-items: center;
            background: #3c3c3c;
            border: 1px solid #3c3c3c;
            height: 26px;
            transition: border-color 0.2s;
        `
        
        searchInputContainer.innerHTML = `
            <button class="toggle-replace-btn" title="切换替换模式" style="
                background: none;
                border: none;
                color: #cccccc;
                padding: 4px 6px;
                cursor: pointer;
                font-size: 12px;
                display: flex;
                align-items: center;
                justify-content: center;
                opacity: 0.7;
                transition: all 0.2s;
                width: 22px;
                height: 22px;
            " onmouseover="this.style.opacity='1'; this.style.backgroundColor='#464647'" 
               onmouseout="this.style.opacity='0.7'; this.style.backgroundColor='transparent'">▶</button>
            <input type="text" class="search-input" placeholder="查找" style="
                flex: 1;
                background: transparent;
                border: none;
                color: #cccccc;
                padding: 4px 6px;
                font-size: 13px;
                outline: none;
                height: 100%;
            ">
            <div class="search-options" style="display: flex; margin-right: 4px;">
                <button class="search-option-btn case-sensitive-btn" title="区分大小写 (Alt+C)" style="
                    background: none;
                    border: none;
                    color: #858585;
                    padding: 2px 4px;
                    cursor: pointer;
                    font-size: 11px;
                    font-weight: 600;
                    width: 22px;
                    height: 22px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    transition: all 0.2s;
                ">Aa</button>
                <button class="search-option-btn whole-word-btn" title="全字匹配 (Alt+W)" style="
                    background: none;
                    border: none;
                    color: #858585;
                    padding: 2px 4px;
                    cursor: pointer;
                    font-size: 11px;
                    font-weight: 600;
                    width: 22px;
                    height: 22px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    transition: all 0.2s;
                ">Ab</button>
                <button class="search-option-btn regex-btn" title="使用正则表达式 (Alt+R)" style="
                    background: none;
                    border: none;
                    color: #858585;
                    padding: 2px 4px;
                    cursor: pointer;
                    font-size: 11px;
                    font-weight: 600;
                    width: 22px;
                    height: 22px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    transition: all 0.2s;
                ">.*</button>
            </div>
            <div class="search-navigation" style="display: flex; border-left: 1px solid #464647; margin-left: 4px;">
                <button class="find-prev-btn" title="上一个 (Shift+F3)" style="
                    background: none;
                    border: none;
                    color: #cccccc;
                    padding: 0;
                    cursor: pointer;
                    font-size: 12px;
                    width: 24px;
                    height: 22px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    transition: all 0.2s;
                    opacity: 0.7;
                " onmouseover="this.style.opacity='1'; this.style.backgroundColor='#464647'" 
                   onmouseout="this.style.opacity='0.7'; this.style.backgroundColor='transparent'">↑</button>
                <button class="find-next-btn" title="下一个 (F3)" style="
                    background: none;
                    border: none;
                    color: #cccccc;
                    padding: 0;
                    cursor: pointer;
                    font-size: 12px;
                    width: 24px;
                    height: 22px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    transition: all 0.2s;
                    opacity: 0.7;
                " onmouseover="this.style.opacity='1'; this.style.backgroundColor='#464647'" 
                   onmouseout="this.style.opacity='0.7'; this.style.backgroundColor='transparent'">↓</button>
            </div>
        `
        
        searchSection.appendChild(searchInputContainer)
        
        // 创建替换区域（默认隐藏）
        this.replaceSection = document.createElement('div')
        this.replaceSection.className = 'replace-section'
        this.replaceSection.style.cssText = `
            padding: 0 8px 6px 8px;
            background: #252526;
            display: none;
        `
        
        // 替换输入框容器
        const replaceInputContainer = document.createElement('div')
        replaceInputContainer.style.cssText = `
            display: flex;
            align-items: center;
            background: #3c3c3c;
            border: 1px solid #3c3c3c;
            height: 26px;
            margin-top: 4px;
            transition: border-color 0.2s;
        `
        
        replaceInputContainer.innerHTML = `
            <div style="width: 22px; height: 22px; margin-left: 6px;"></div>
            <input type="text" class="replace-input" placeholder="替换" style="
                flex: 1;
                background: transparent;
                border: none;
                color: #cccccc;
                padding: 4px 6px;
                font-size: 13px;
                outline: none;
                height: 100%;
            ">
            <div class="replace-actions" style="display: flex; margin-right: 4px;">
                <button class="replace-btn" title="替换 (Ctrl+Shift+1)" style="
                    background: none;
                    border: none;
                    color: #cccccc;
                    padding: 0;
                    cursor: pointer;
                    font-size: 12px;
                    width: 22px;
                    height: 22px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    transition: all 0.2s;
                    opacity: 0.7;
                " onmouseover="this.style.opacity='1'; this.style.backgroundColor='#464647'" 
                   onmouseout="this.style.opacity='0.7'; this.style.backgroundColor='transparent'">↻</button>
                <button class="replace-all-btn" title="全部替换 (Ctrl+Alt+Enter)" style="
                    background: none;
                    border: none;
                    color: #cccccc;
                    padding: 0;
                    cursor: pointer;
                    font-size: 12px;
                    width: 22px;
                    height: 22px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    transition: all 0.2s;
                    opacity: 0.7;
                " onmouseover="this.style.opacity='1'; this.style.backgroundColor='#464647'" 
                   onmouseout="this.style.opacity='0.7'; this.style.backgroundColor='transparent'">⇻</button>
            </div>
        `
        
        this.replaceSection.appendChild(replaceInputContainer)
        
        // 创建结果显示区域
        const resultSection = document.createElement('div')
        resultSection.className = 'search-result-section'
        resultSection.style.cssText = `
            padding: 4px 8px;
            background: #2d2d30;
            border-top: 1px solid #3c3c3c;
            font-size: 11px;
            color: #858585;
            min-height: 20px;
            display: flex;
            align-items: center;
        `
        resultSection.innerHTML = '<span class="search-result">请输入搜索内容</span>'
        
        // 组装对话框
        this.searchDialog.appendChild(titleBar)
        this.searchDialog.appendChild(searchSection)
        this.searchDialog.appendChild(this.replaceSection)
        this.searchDialog.appendChild(resultSection)
        
        // 添加到页面
        document.body.appendChild(this.searchDialog)
        
        // 获取元素引用
        this.searchInput = this.searchDialog.querySelector('.search-input')
        this.replaceInput = this.searchDialog.querySelector('.replace-input')
        this.resultElement = this.searchDialog.querySelector('.search-result')
        this.toggleReplaceBtn = this.searchDialog.querySelector('.toggle-replace-btn')
        
        // 获取选项按钮
        this.caseSensitiveBtn = this.searchDialog.querySelector('.case-sensitive-btn')
        this.wholeWordBtn = this.searchDialog.querySelector('.whole-word-btn')
        this.regexBtn = this.searchDialog.querySelector('.regex-btn')
        
        // 设置拖拽功能
        this.setupDragging(titleBar)
        
        // 添加输入框焦点效果和按钮状态管理
        this.setupInputEffects()
        this.setupButtonStates()
        
        // 绑定事件
        this.bindSearchDialogEvents()
    }
    
    /**
     * 绑定搜索对话框事件
     */
    bindSearchDialogEvents() {
        // 安全检查 - 确保所有必需的DOM元素都存在
        if (!this.searchInput || !this.replaceInput || !this.toggleReplaceBtn) {
            logger.error('搜索框DOM元素未正确初始化:', {
                searchInput: !!this.searchInput,
                replaceInput: !!this.replaceInput,
                toggleReplaceBtn: !!this.toggleReplaceBtn
            })
            return
        }
        
        // 关闭按钮
        const closeBtn = this.searchDialog.querySelector('.close-btn')
        if (closeBtn) {
            closeBtn.addEventListener('click', (e) => {
                e.stopPropagation()
                this.hideSearch()
            })
        }
        
        // 切换替换框按钮
        this.toggleReplaceBtn.addEventListener('click', (e) => {
            e.stopPropagation()
            this.toggleReplace()
        })
        
        // 搜索输入
        this.searchInput.addEventListener('input', (e) => {
            e.stopPropagation()
            e.stopImmediatePropagation()  // 阻止所有事件冒泡
            this.searchText = this.searchInput.value
            this.performSearch()
        })
        
        // 替换输入
        this.replaceInput.addEventListener('input', (e) => {
            e.stopPropagation()
            e.stopImmediatePropagation()  // 阻止所有事件冒泡
            this.replaceText = this.replaceInput.value
        })
        
        // 选项按钮事件
        if (this.caseSensitiveBtn) {
            this.caseSensitiveBtn.addEventListener('click', (e) => {
                e.stopPropagation()
                this.options.caseSensitive = !this.options.caseSensitive
                this.updateButtonState(this.caseSensitiveBtn, this.options.caseSensitive)
                this.performSearch()
            })
        }
        
        if (this.wholeWordBtn) {
            this.wholeWordBtn.addEventListener('click', (e) => {
                e.stopPropagation()
                this.options.wholeWord = !this.options.wholeWord
                this.updateButtonState(this.wholeWordBtn, this.options.wholeWord)
                this.performSearch()
            })
        }
        
        if (this.regexBtn) {
            this.regexBtn.addEventListener('click', (e) => {
                e.stopPropagation()
                this.options.useRegex = !this.options.useRegex
                this.updateButtonState(this.regexBtn, this.options.useRegex)
                this.performSearch()
            })
        }
        
        // 按钮事件
        const findPrevBtn = this.searchDialog.querySelector('.find-prev-btn')
        if (findPrevBtn) {
            findPrevBtn.addEventListener('click', (e) => {
                e.stopPropagation()
                this.findPrevious()
            })
        }
        
        const findNextBtn = this.searchDialog.querySelector('.find-next-btn')
        if (findNextBtn) {
            findNextBtn.addEventListener('click', (e) => {
                e.stopPropagation()
                this.findNext()
            })
        }
        
        const replaceBtn = this.searchDialog.querySelector('.replace-btn')
        if (replaceBtn) {
            replaceBtn.addEventListener('click', (e) => {
                e.stopPropagation()
                this.replaceCurrent()
            })
        }
        
        const replaceAllBtn = this.searchDialog.querySelector('.replace-all-btn')
        if (replaceAllBtn) {
            replaceAllBtn.addEventListener('click', (e) => {
                e.stopPropagation()
                this.replaceAll()
            })
        }
        
        // 键盘事件 - 正确的焦点管理
        this.searchInput.addEventListener('keydown', (e) => {
            e.stopPropagation()
            e.stopImmediatePropagation()  // 阻止所有事件冒泡
            this.handleSearchInputKeydown(e)
        })
        
        this.replaceInput.addEventListener('keydown', (e) => {
            e.stopPropagation()
            e.stopImmediatePropagation()  // 阻止所有事件冒泡
            this.handleReplaceInputKeydown(e)
        })
        
        // 为输入框添加更全面的事件隔离（但不包含 input 事件）
        const inputElements = [this.searchInput, this.replaceInput]
        for (let i = 0; i < inputElements.length; i++) {
            const input = inputElements[i]
            if (!input || typeof input.addEventListener !== 'function') {
                logger.warn('输入框元素不存在或无效，跳过事件绑定:', input)
                continue
            }
            
            // 阻止部分干扰事件（但保留 input 事件）
            const eventTypes = ['keyup', 'keypress', 'focus', 'blur', 'mousedown', 'mouseup', 'click']
            for (let j = 0; j < eventTypes.length; j++) {
                const eventType = eventTypes[j]
                try {
                    input.addEventListener(eventType, (e) => {
                        e.stopPropagation()
                        if (eventType === 'keyup' || eventType === 'keypress') {
                            e.stopImmediatePropagation()
                        }
                    }, true)  // 使用捕获阶段
                } catch (error) {
                    logger.error(`绑定事件 ${eventType} 失败:`, error)
                }
            }
        }
        
        // 防止对话框事件冒泡
        this.searchDialog.addEventListener('mousedown', (e) => {
            e.stopPropagation()
        })
        
        this.searchDialog.addEventListener('click', (e) => {
            e.stopPropagation()
        })
        
        this.searchDialog.addEventListener('keydown', (e) => {
            e.stopPropagation()
        })
        
        // 增强的焦点管理 - 不强制保持焦点
        this.setupFocusManagement()
    }
    
    /**
     * 处理搜索输入框的键盘事件
     */
    handleSearchInputKeydown(e) {
        // 快捷键切换搜索选项
        if (e.altKey) {
            switch (e.key.toLowerCase()) {
                case 'c':
                    e.preventDefault()
                    this.options.caseSensitive = !this.options.caseSensitive
                    this.updateButtonState(this.caseSensitiveBtn, this.options.caseSensitive)
                    this.performSearch()
                    return
                case 'w':
                    e.preventDefault()
                    this.options.wholeWord = !this.options.wholeWord
                    this.updateButtonState(this.wholeWordBtn, this.options.wholeWord)
                    this.performSearch()
                    return
                case 'r':
                    e.preventDefault()
                    this.options.useRegex = !this.options.useRegex
                    this.updateButtonState(this.regexBtn, this.options.useRegex)
                    this.performSearch()
                    return
            }
        }
        
        switch (e.key) {
            case 'Enter':
                e.preventDefault()
                if (e.shiftKey) {
                    this.findPrevious()
                } else {
                    this.findNext()
                }
                break
            case 'Escape':
                e.preventDefault()
                this.hideSearch()
                break
            case 'Tab':
                if (this.isReplaceVisible) {
                    e.preventDefault()
                    this.replaceInput.focus()
                }
                break
            case 'ArrowDown':
                if (this.isReplaceVisible) {
                    e.preventDefault()
                    this.replaceInput.focus()
                }
                break
        }
    }
    
    /**
     * 处理替换输入框的键盘事件
     */
    handleReplaceInputKeydown(e) {
        // 快捷键切换搜索选项（与搜索输入框保持一致）
        if (e.altKey) {
            switch (e.key.toLowerCase()) {
                case 'c':
                    e.preventDefault()
                    this.options.caseSensitive = !this.options.caseSensitive
                    this.updateButtonState(this.caseSensitiveBtn, this.options.caseSensitive)
                    this.performSearch()
                    return
                case 'w':
                    e.preventDefault()
                    this.options.wholeWord = !this.options.wholeWord
                    this.updateButtonState(this.wholeWordBtn, this.options.wholeWord)
                    this.performSearch()
                    return
                case 'r':
                    e.preventDefault()
                    this.options.useRegex = !this.options.useRegex
                    this.updateButtonState(this.regexBtn, this.options.useRegex)
                    this.performSearch()
                    return
            }
        }
        
        switch (e.key) {
            case 'Enter':
                e.preventDefault()
                if (e.ctrlKey) {
                    this.replaceAll()
                } else {
                    this.replaceCurrent()
                }
                break
            case 'Escape':
                e.preventDefault()
                this.hideSearch()
                break
            case 'Tab':
                if (e.shiftKey) {
                    e.preventDefault()
                    this.searchInput.focus()
                }
                break
            case 'ArrowUp':
                e.preventDefault()
                this.searchInput.focus()
                break
        }
    }
    
    /**
     * 切换替换框显示
     */
    toggleReplace() {
        this.isReplaceVisible = !this.isReplaceVisible
        
        if (this.isReplaceVisible) {
            this.replaceSection.style.display = 'block'
            this.toggleReplaceBtn.innerHTML = '▼'  // 下箭头
            this.toggleReplaceBtn.style.transform = 'rotate(90deg)'
        } else {
            this.replaceSection.style.display = 'none'
            this.toggleReplaceBtn.innerHTML = '▶'  // 右箭头
            this.toggleReplaceBtn.style.transform = 'rotate(0deg)'
        }
    }
    
    /**
     * 设置拖拽功能
     */
    setupDragging(titleBar) {
        let isDragging = false
        let startX, startY
        let initialX, initialY
        
        titleBar.addEventListener('mousedown', (e) => {
            if (e.target.classList.contains('close-btn')) return
            
            isDragging = true
            startX = e.clientX
            startY = e.clientY
            
            const rect = this.searchDialog.getBoundingClientRect()
            initialX = rect.left
            initialY = rect.top
            
            titleBar.style.cursor = 'grabbing'
            
            const handleMouseMove = (e) => {
                if (!isDragging) return
                
                const deltaX = e.clientX - startX
                const deltaY = e.clientY - startY
                
                let newX = initialX + deltaX
                let newY = initialY + deltaY
                
                // 边界检查
                const maxX = window.innerWidth - this.searchDialog.offsetWidth
                const maxY = window.innerHeight - this.searchDialog.offsetHeight
                
                newX = Math.max(0, Math.min(newX, maxX))
                newY = Math.max(0, Math.min(newY, maxY))
                
                this.searchDialog.style.left = newX + 'px'
                this.searchDialog.style.top = newY + 'px'
                this.searchDialog.style.right = 'auto'  // 移除右对齐
            }
            
            const handleMouseUp = () => {
                isDragging = false
                titleBar.style.cursor = 'move'
                document.removeEventListener('mousemove', handleMouseMove)
                document.removeEventListener('mouseup', handleMouseUp)
            }
            
            document.addEventListener('mousemove', handleMouseMove)
            document.addEventListener('mouseup', handleMouseUp)
        })
    }
        
    /**
     * 设置输入框焦点效果
     */
    setupInputEffects() {
        // 为输入框添加焦点效果
        const addFocusEffect = (container, input) => {
            input.addEventListener('focus', () => {
                container.style.borderColor = '#007acc'
                container.style.boxShadow = '0 0 0 1px #007acc'
            })
                
            input.addEventListener('blur', () => {
                container.style.borderColor = '#5a5a5c'
                container.style.boxShadow = 'none'
            })
        }
            
        const searchContainer = this.searchInput.closest('div')
        const replaceContainer = this.replaceInput.closest('div')
            
        addFocusEffect(searchContainer, this.searchInput)
        addFocusEffect(replaceContainer, this.replaceInput)
    }
        
    /**
     * 设置按钮状态
     */
    setupButtonStates() {
        // 初始化按钮状态
        this.updateButtonState(this.caseSensitiveBtn, this.options.caseSensitive)
        this.updateButtonState(this.wholeWordBtn, this.options.wholeWord)
        this.updateButtonState(this.regexBtn, this.options.useRegex)
            
        // 为按钮添加悬停效果（与激活状态兼容）
        const buttons = [this.caseSensitiveBtn, this.wholeWordBtn, this.regexBtn]
        buttons.forEach(btn => {
            if (!btn) return
            
            btn.addEventListener('mouseenter', () => {
                if (!btn.classList.contains('active')) {
                    btn.style.backgroundColor = '#464647'
                } else {
                    // 激活状态下的悬停效果
                    btn.style.backgroundColor = '#1177bb'
                }
            })
                
            btn.addEventListener('mouseleave', () => {
                if (!btn.classList.contains('active')) {
                    btn.style.backgroundColor = 'transparent'
                } else {
                    // 恢复激活状态的背景色
                    btn.style.backgroundColor = '#007acc'
                }
            })
        })
    }
        
    /**
     * 更新按钮状态
     */
    updateButtonState(button, isActive) {
        if (isActive) {
            button.classList.add('active')
            button.style.backgroundColor = '#007acc'
            button.style.color = '#ffffff'
        } else {
            button.classList.remove('active')
            button.style.backgroundColor = 'transparent'
            button.style.color = '#858585'
        }
    }
        
    /**
     * 设置焦点管理
     */
    setupFocusManagement() {
        // 简化的焦点管理 - 完全不干预焦点流转
        // 只设置事件隔离，让用户可以完全自由地在搜索框和编辑器之间切换
    }
    
    /**
     * 处理键盘事件
     */
    handleKeyDown(data) {
        const e = data.event
        
        // 如果事件来自搜索框内部，就不处理
        if (this.isSearchVisible && this.searchDialog.contains(e.target)) {
            return false  // 让搜索框内部自己处理事件
        }
        
        // Ctrl+F 打开搜索
        if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
            e.preventDefault()
            this.showSearch()
            return true
        }
        
        // Ctrl+H 打开搜索替换
        if ((e.ctrlKey || e.metaKey) && e.key === 'h') {
            e.preventDefault()
            this.showSearch(true)
            return true
        }
        
        // 当搜索框可见时的快捷键（但不在搜索框内）
        if (this.isSearchVisible) {
            if (e.key === 'Escape') {
                e.preventDefault()
                this.hideSearch()
                return true
            }
            
            if ((e.ctrlKey || e.metaKey) && e.key === 'g') {
                e.preventDefault()
                if (e.shiftKey) {
                    this.findPrevious()
                } else {
                    this.findNext()
                }
                return true
            }
        }
        
        // 如果没有处理任何事件，返回false
        return false
    }
    
    /**
     * 显示搜索对话框
     */
    showSearch(openReplace = false) {
        this.isSearchVisible = true
        this.searchDialog.style.display = 'block'
        
        // 如果要打开替换模式
        if (openReplace && !this.isReplaceVisible) {
            this.toggleReplace()
        }
        
        // 如果有选中文本，自动填入搜索框
        const selectedText = this.getSelectedText()
        if (selectedText) {
            this.searchInput.value = selectedText
            this.searchText = selectedText
            this.performSearch()
        }
        
        // 聚焦到相应输入框
        setTimeout(() => {
            if (openReplace && this.isReplaceVisible && this.replaceInput) {
                this.replaceInput.focus()
                this.replaceInput.select()
            } else {
                this.searchInput.focus()
                this.searchInput.select()
            }
        }, 50) // 给一点延迟确保DOM已更新
        
        this.emit('searchReplace:shown')
    }
    
    /**
     * 隐藏搜索对话框
     */
    hideSearch() {
        this.isSearchVisible = false
        this.searchDialog.style.display = 'none'
        this.clearHighlights()
        
        // 恢复编辑器焦点
        this.editor.editor.focus()
        
        this.emit('searchReplace:hidden')
    }
    
    /**
     * 执行搜索
     */
    performSearch() {
        this.clearHighlights()
        this.matches = []
        this.currentIndex = -1
        
        if (!this.searchText) {
            this.updateResult('请输入搜索内容')
            return
        }
        
        try {
            const text = this.editor.editor.value
            const regex = this.buildSearchRegex()
            
            let match
            while ((match = regex.exec(text)) !== null) {
                this.matches.push({
                    start: match.index,
                    end: match.index + match[0].length,
                    text: match[0]
                })
                
                // 防止无限循环
                if (!regex.global) break
            }
            
            if (this.matches.length > 0) {
                this.createHighlights()
                this.currentIndex = 0
                this.highlightCurrent()
                this.updateResult(`找到 ${this.matches.length} 个匹配项`)
            } else {
                this.updateResult('未找到匹配项')
            }
            
        } catch (error) {
            this.updateResult('搜索表达式错误')
            logger.error('搜索错误:', error)
        }
    }
    
    /**
     * 构建搜索正则表达式
     */
    buildSearchRegex() {
        let pattern = this.searchText
        let flags = 'g'
        
        if (!this.options.caseSensitive) {
            flags += 'i'
        }
        
        if (!this.options.useRegex) {
            // 转义特殊字符
            pattern = pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
        }
        
        if (this.options.wholeWord) {
            pattern = `\\b${pattern}\\b`
        }
        
        return new RegExp(pattern, flags)
    }
    
    /**
     * 创建搜索高亮
     */
    createHighlights() {
        // 这里创建搜索高亮的视觉效果
        // 可以通过CSS和DOM操作实现
        this.matches.forEach((match, index) => {
            // 创建高亮标记（简化实现）
            this.highlights.push({
                start: match.start,
                end: match.end,
                index: index
            })
        })
    }
    
    /**
     * 清除高亮
     */
    clearHighlights() {
        this.highlights = []
        this.currentHighlight = null
        // 清除视觉高亮效果
    }
    
    /**
     * 高亮当前匹配项
     */
    highlightCurrent() {
        if (this.currentIndex >= 0 && this.currentIndex < this.matches.length) {
            const match = this.matches[this.currentIndex]
            
            // 移动光标到匹配位置
            this.editor.editor.setSelectionRange(match.start, match.end)
            this.editor.editor.focus()
            
            // 滚动到可视区域
            this.scrollToSelection()
            
            this.updateResult(`${this.currentIndex + 1} / ${this.matches.length}`)
        }
    }
    
    /**
     * 查找下一个
     */
    findNext() {
        if (this.matches.length === 0) {
            this.performSearch()
            return
        }
        
        this.currentIndex = (this.currentIndex + 1) % this.matches.length
        this.highlightCurrent()
    }
    
    /**
     * 查找上一个
     */
    findPrevious() {
        if (this.matches.length === 0) {
            this.performSearch()
            return
        }
        
        this.currentIndex = (this.currentIndex - 1 + this.matches.length) % this.matches.length
        this.highlightCurrent()
    }
    
    /**
     * 替换当前匹配项
     */
    replaceCurrent() {
        if (this.currentIndex >= 0 && this.currentIndex < this.matches.length) {
            const match = this.matches[this.currentIndex]
            const text = this.editor.editor.value
            
            // 执行替换
            const newText = text.substring(0, match.start) + 
                          this.replaceText + 
                          text.substring(match.end)
            
            this.editor.editor.value = newText
            
            // 更新编辑器状态
            this.editor._updateEditor()
            this.editor._updateStatus()
            
            // 重新搜索
            this.performSearch()
            
            this.emit('searchReplace:replaced', { 
                count: 1,
                searchText: this.searchText,
                replaceText: this.replaceText
            })
        }
    }
    
    /**
     * 替换全部
     */
    replaceAll() {
        if (this.matches.length === 0) {
            return
        }
        
        const text = this.editor.editor.value
        const regex = this.buildSearchRegex()
        const newText = text.replace(regex, this.replaceText)
        
        this.editor.editor.value = newText
        
        // 更新编辑器状态
        this.editor._updateEditor()
        this.editor._updateStatus()
        
        const count = this.matches.length
        this.updateResult(`已替换 ${count} 处`)
        
        // 清除搜索结果
        this.clearHighlights()
        this.matches = []
        this.currentIndex = -1
        
        this.emit('searchReplace:replacedAll', { 
            count,
            searchText: this.searchText,
            replaceText: this.replaceText
        })
    }
    
    /**
     * 获取选中文本
     */
    getSelectedText() {
        const start = this.editor.editor.selectionStart
        const end = this.editor.editor.selectionEnd
        if (start !== end) {
            return this.editor.editor.value.substring(start, end)
        }
        return ''
    }
    
    /**
     * 滚动到选择区域
     */
    scrollToSelection() {
        // 简化实现：让编辑器聚焦即可自动滚动
        this.editor.editor.focus()
    }
    
    /**
     * 更新结果显示
     */
    updateResult(message) {
        if (this.resultElement) {
            this.resultElement.textContent = message
        }
    }
    
    /**
     * 发射事件的便捷方法
     */
    emit(event, data) {
        this.editor.emit(event, data)
    }
    
    /**
     * 获取当前配置
     */
    getConfig() {
        return {
            caseSensitive: this.options.caseSensitive,
            wholeWord: this.options.wholeWord,
            useRegex: this.options.useRegex,
            wrapSearch: this.options.wrapSearch
        }
    }
    
    /**
     * 设置搜索选项
     */
    setSearchOptions(options) {
        Object.assign(this.options, options)
        
        // 更新UI按钮状态
        if (this.caseSensitiveBtn) {
            this.updateButtonState(this.caseSensitiveBtn, this.options.caseSensitive)
        }
        if (this.wholeWordBtn) {
            this.updateButtonState(this.wholeWordBtn, this.options.wholeWord)
        }
        if (this.regexBtn) {
            this.updateButtonState(this.regexBtn, this.options.useRegex)
        }
        
        // 重新搜索
        if (this.searchText) {
            this.performSearch()
        }
    }
}